<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>常用组件开发--输入框</title>
  <script src="js/vue.js"></script>
</head>
<body>
  <div id="app">
    <input-number v-model="value" :step="4" :max='20' :min="1" @input="inputEvent"></input-number>
  </div>

  <script>
    Vue.component('input-number', {
      template: '\
      <div class="input-number">\
        <input type="text" :value="currentValue"/>\
        <button @click="handleDown" :disabled="currentValue <= min">-</button>\
        <button @click="handleUp" :disabled="currentValue >= max">+</button>\
      </div>\
      ',
      props: {
        value: {
          type: Number,
          default: 0
        },
        step: {
          type: Number,
          default: 1
        },
        min: {
          type: Number,
          default: -Infinity
        },
        max: {
          type: Number,
          default: Infinity
        }
      },
      data(){
        return {
          currentValue: this.value
        }
      },
      methods: {
        handleUp() {
          if(this.currentValue >= this.max) return;
          this.currentValue += this.step;
        },
        handleDown() {
          if(this.currentValue <= this.min) return;
          this.currentValue -= this.step;
        },
        updataValue(val) {
          if(this.currentValue > this.max) val = this.max;
          if(this.currentValue < this.min) val= this.min;
          this.currentValue = val;
        }
      },
      watch: {
        currentValue(val) {
          this.$emit('input', val);
        },
        value(val) { 
          this.updataValue(val);
        }
      },
      mounted(){
        this.updataValue(this.value);
      }
    })
    var app = new Vue({
      el: '#app',
      data() {
        return {
          value: 21
        }
      },
      methods: {
        //监听子组件触发出来的事件
        inputEvent(val) {
          console.log(val);
        }
      }
    })
  </script>
  
</body>
</html>